<template>
  <view class="container">
    <image class="goods-image" :src="goods.images" mode="aspectFill" @click="openImagePreview(goods.images)"></image>
    
    <view class="shop-link" @click="goToShop(goods.shopId)">
      <image class="shop-icon" src="/static/shop.png" mode="aspectFill"></image>
      <text class="shop-text">点击了解更多商店好物</text>
    </view>
    
    <view class="goods-details"> 
      <text class="goods-name">{{ goods.goodsName }}</text>
      <text class="goods-description">{{ goods.description }}</text>
      <text class="goods-price"> ¥ {{ goods.price }}</text>

      <view class="user-reviews">
        <text class="review-title">用户评价（{{ filteredReviews.length }}）</text>
        <view v-for="review in filteredReviews" :key="review.id" class="review">
          <view class="review-header">
            <image class="review-avatar" :src="review.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
            <text class="review-author">{{ review.author }}</text>
          </view>
          <text class="review-text">{{ review.text }}</text>
        </view>
      </view>
    </view>
    
    <view class="button-area">
      <button class="add-to-cart" @click="openAddToCartModal">加入购物车</button>
      <button class="buy-now" @click="openPurchaseModal">购买</button>
    </view>

    <view class="modal" v-if="showPurchaseModal">
      <view class="modal-content">
        <view class="modal-header">
         <text>确认购买</text>
        </view>
        <view class="modal-body">
          <text>当前库存: {{ goods.goodsCount }}</text>
          <view class="quantity-input">
            <button @click="purchaseQuantity > 1 && purchaseQuantity--">-</button>
            <input type="number" v-model.number="purchaseQuantity" @input="setPurchaseQuantity" />
            <button @click="purchaseQuantity < goods.goodsCount && purchaseQuantity++">+</button>
          </view>
        </view>
        <view class="modal-footer">
          <button @click="confirmPurchase" class="confirm-button">确认购买</button>
          <button @click="closePurchaseModal" class="cancel-button">取消</button>
        </view>
      </view>
    </view>

    <view class="modal" v-if="showAddToCartModal">
      <view class="modal-content">
        <view class="modal-header">
         <text>确认加入购物车</text>
        </view>
        <view class="modal-body">
          <text>当前库存: {{ goods.goodsCount }}</text>
          <view class="quantity-input">
            <button @click="addToCartQuantity > 1 && addToCartQuantity--">-</button>
            <input type="number" v-model.number="addToCartQuantity" @input="setAddToCartQuantity" />
            <button @click="addToCartQuantity < goods.goodsCount && addToCartQuantity++">+</button>
          </view>
        </view>
        <view class="modal-footer">
          <button @click="addToCart" class="confirm-button">确认加入购物车</button>
          <button @click="closeAddToCartModal" class="cancel-button">取消</button>
        </view>
      </view>
    </view>

    <view class="image-preview-modal" v-if="isPreviewVisible" @click="closeImagePreview">
      <image class="preview-image" :src="previewImageUrl" mode="aspectFit"></image>
    </view>
  </view>
</template>

<script>
import config from '@/config';

export default {
  data() {
    return {
      goods: {},
      goodsId: null,
      reviews: [],
      showPurchaseModal: false,
      showAddToCartModal: false, // 新增
      purchaseQuantity: 1,
      addToCartQuantity: 1, // 新增
      previewImageUrl: '',
      isPreviewVisible: false,
    };
  },
  onLoad(options) {
    this.goodsId = options.goodsId;
    this.fetchGoodsDetails();
  },
  computed: {
    filteredReviews() {
      return this.reviews.filter(review => review.text && review.text.trim() !== '');
    }
  },
  methods: { 
    fetchGoodsDetails() { 
      uni.request({
        url: `${config.apiUrl}/goods/details/${this.goodsId}`,
        method: 'GET',
        data: { id: this.goodsId },
        success: (response) => {
          this.goods = response.data;

          uni.request({
            url: `${config.apiUrl}/order/remarks`,
            method: 'GET',
            data: {
              goodsName: this.goods.goodsName
            },
            success: (response) => {
              if (response.data) {
                this.reviews = response.data.map(order => ({
                  id: order.orderId || Math.random(),
                  text: order.remark,
                  author: order.nickName
                }));
                // 获取每个作者的头像
                this.reviews.forEach((review, index) => {
                  uni.request({
                    url: `${config.apiUrl}/user/avatarByNickname`,
                    method: 'GET',
                    data: { nickname: review.author },
                    success: (avatarResponse) => {
                      // 返回头头像路径赋值给review
                      if (avatarResponse.data) {
                        this.$set(this.reviews, index, { ...review, avatar: avatarResponse.data });
                      }
                    }
                  });
                });
              }
            },
            fail: (error) => {
              console.error('Error fetching remarks:', error);
            }
          });
        },
        fail: (error) => {
          console.error('Error fetching goods details:', error);
        }
      });
    },
    openAddToCartModal() {
      this.showAddToCartModal = true;
    },
    closeAddToCartModal() {
      this.showAddToCartModal = false;
    },
    openPurchaseModal() {
      this.showPurchaseModal = true;
    },
    closePurchaseModal() {
      this.showPurchaseModal = false;
    },
    addToCart() {
        if (this.addToCartQuantity > this.goods.goodsCount) {
          uni.showToast({
            title: '库存不足',
            icon: 'none'
          });
          return;
        }
    
        const cartItem = {
          goodsId: this.goods.goodsId,
          goodsName: this.goods.goodsName,
          description: this.goods.description,
          images: this.goods.images,
          price: this.goods.price,
          shopId: this.goods.shopId,
          quantity: this.addToCartQuantity // 添加数量
        };
       console.log("加入到购物车的商品的数量：",this.addToCartQuantity);
        uni.request({
          url: `${config.apiUrl}/carts/add`,
          method: 'POST',
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          data: cartItem,
          success: (response) => {
            if (response.data) {
              uni.showToast({
                title: '成功加入购物车',
                icon: 'success'
              });
              this.closeAddToCartModal();
              // 更新购物车数据
              this.updateCart();
              uni.$emit('cartUpdated'); // 发出购物车更新事件
            } else {
              uni.showToast({
                title: '加入购物车失败',
                icon: 'none'
              });
            }
          },
          fail: (error) => {
            console.error('Error adding to cart:', error);
            uni.showToast({
              title: '网络错误',
              icon: 'none'
            });
          }
        });
      },
     updateCart() {
       uni.request({
         url: `${config.apiUrl}/carts/getbyuserid`,
         method: 'GET',
         success: (res) => {
           if (res.statusCode === 200) {
             this.cartslist = res.data; // 更新购物车数据
             uni.setStorageSync('cartslist', this.cartslist); // 缓存购物车数据
           } else {
             console.error('Failed to fetch carts:', res);
           }
         },
         fail: (err) => {
           console.error('Request failed:', err);
         }
       });
     },
    goToShop(shopId) {
      uni.navigateTo({
        url: `/pages/shop/shop?shopId=${shopId}`
      });
    },
    confirmPurchase() {
      const goodsData = {
        name: this.goods.goodsName,
        price: this.goods.price,
        quantity: this.purchaseQuantity,
        images: this.goods.images,
        shopId: this.goods.shopId,
      };
      uni.setStorageSync('goodsData', goodsData);

      uni.navigateTo({
        url: '/pages/shopping/confirm2'
      });
      this.showPurchaseModal = false;
    },
    setPurchaseQuantity(event) {
      const value = parseInt(event.target.value);
      if (value > this.goods.goodsCount) {
          this.purchaseQuantity = this.goods.goodsCount;
      } else if (value < 1) {
          this.purchaseQuantity = 1;
      } else {
          this.purchaseQuantity = value;
      }
    },
    setAddToCartQuantity(event) {
      const value = parseInt(event.target.value);
      if (value > this.goods.goodsCount) {
          this.addToCartQuantity = this.goods.goodsCount;
      } else if (value < 1) {
          this.addToCartQuantity = 1;
      } else {
          this.addToCartQuantity = value;
      }
    },
    openImagePreview(imageUrl) {
      this.previewImageUrl = imageUrl;
      this.isPreviewVisible = true;
    },
    closeImagePreview() {
      this.isPreviewVisible = false;
      this.previewImageUrl = '';
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 20rpx;
  background-color: #ffefba;
}

.goods-image {
  width: 100%;
  height: 55vh;
}

.goods-details {
  width: 95%;
  padding: 20rpx;
  text-align: left;
  margin-top: 20rpx;
  background-color: #EACD6F;
  border-radius: 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.goods-name {
  font-size: 55rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  display: block;
  padding: 10px;
}

.goods-description {
  font-size: 36rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
  padding-bottom: 10px;
  padding-left: 10px;
}

.goods-price {
  font-size: 48rpx;
  color: orangered;
  display: block;
  text-align: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.shop-link {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  cursor: pointer;
}

.shop-icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 10rpx;
}

.shop-text {
  font-size: 36rpx;
  color: #87BC32;
}

.user-reviews {
  width: 94%;
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.review-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.review {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.review-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 10rpx;
}

.review-author {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.review-text {
  font-size: 32rpx;
  color: #333;
}

.button-area {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20rpx;
}

.button-area button {
  width: 250rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #87BC32;
  color: #fff;
  border: none;
  border-radius: 30rpx;
  font-size: 35rpx;
  margin-left: 10rpx;
}

.add-to-cart {
  background-color: #f60;
}

.buy-now {
  background-color: #f30;
}

.modal {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
}

.modal-content {
  width: 90%;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx;
  position: relative;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 36rpx;
  margin-bottom: 20rpx;
}

.close-button {
  background: none;
  border: none;
  font-size: 36rpx;
  cursor: pointer;
}

.modal-body {
  font-size: 32rpx;
  margin-bottom: 20rpx;
}

.quantity-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.quantity-input button {
  width: 50rpx;
  height: 50rpx;
  background-color: #87BC32;
  color: #fff;
  border: none;
  border-radius: 50%;
  font-size: 24rpx;
  line-height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-input input {
  width: 100rpx;
  text-align: center;
  border-radius: 10rpx;
  border: 1rpx solid #ccc;
  height: 40rpx;
  margin: 0 10rpx;
}

.modal-footer {
  text-align: right;
}

.confirm-button, .cancel-button {
  background-color: #87BC32;
  color: #fff;
  border: none;
  border-radius: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 32rpx;
  cursor: pointer;
  margin-left: 10rpx;
}

.cancel-button {
  background-color: lightcoral;
}

.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.preview-image {
  max-width: 90%;
  max-height: 90%;
}
</style>
